package core;
import gui.BVView;
import static gui.BVView.*;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;

public class BVController implements ActionListener {
	BVModel bvModel;
	BVView bvView;
	// TODO: implement action listeners for load, save, proeed, export, help
	// TODO: implement methods on each M, V
	public BVController ( BVModel bvModel, BVView bvView ) {
		this.bvModel = bvModel;
		this.bvView = bvView;
		bvView.menuActionListener(this);
		bvView.buttonActionListener(this);
	}
	
	@Override
	public void actionPerformed(ActionEvent event) {
		String action = event.getActionCommand();
		
		if ( action == LOAD_IMAGE) {
			try {
				bvModel.loadImage(bvView.getMainFrame());
				bvModel.initBallDetector();

				
				// TODO : Initiallize the result image
				bvView.setOriginalImage(bvModel.getOriginalImage());
				bvView.setButtonEnable(PROCESS, true);
				bvView.setButtonEnable(SAVE_IMAGE, false);
				bvView.setButtonEnable(EXPORT_DATA, false);
				bvView.setTitle(bvModel.getPath());
				Thread.sleep(500);
			} catch (NullPointerException e) {
				;
			} catch (InterruptedException e) {
				;
			}

		}
		else if ( action == PROCESS ) {
			try {
				bvModel.detectBalls();
				bvModel.detectVoids();
				bvModel.drawResult();
				bvModel.generateData();
				bvView.setResultImage(bvModel.getResultImage());
				bvView.setResultData(bvModel.getDataTable());
				
				bvView.setButtonEnable(PROCESS, false);				
				bvView.setButtonEnable(SAVE_IMAGE, true);
				bvView.setButtonEnable(EXPORT_DATA, true);
			} catch (NullPointerException e) {
				;
			}
		}
		else if ( action == SAVE_IMAGE ) {
			try {
				bvModel.saveImage(bvView.getMainFrame());
			} catch (NullPointerException e) {
				;
			}
		}
		else if ( action == EXPORT_DATA ) {
			try {
				bvModel.exportData(bvView.getMainFrame());
			} catch (NullPointerException e) {
				;
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				;
			}
		}
		else if ( action == ABOUT ) {
			bvView.viewAbout();
		}
		else if ( action == MANUAL_PAGE ) {
			bvView.viewManual();
		}
		else if ( action == EXIT ) {
			// if the action 'exit' is given. exit normally.
			System.exit(0);
		}
		else {
			// if no available command action is given.
			// TODO do something more suitable.
			System.exit(-1);
		}
	}
	
	
}
